// monster-handler.js
/**
 * @file 怪物处理模块
 * @description 处理怪物血量、攻击反馈、重生等逻辑
 */

const { maps, getMapState, resetMonster } = require('./game-state');

/**
 * 处理玩家攻击怪物
 * @param {Socket} socket - 客户端 Socket 实例
 * @param {string} monsterId - 被攻击的怪物 ID
 */
function handleAttack(socket, monsterId) {
  const playerInfo = require('./game-state').findPlayer(socket.id);
  if (!playerInfo) return;

  const { map: currentMap } = playerInfo;
  const monster = maps[currentMap]?.monsters.find(m => m.id === monsterId);
  if (!monster || monster.hp <= 0) return;

  // 计算伤害
  const damage = 10 + Math.floor(Math.random() * 10);

  // 减血
  monster.hp = Math.max(0, monster.hp - damage);

  // 广播攻击效果
  socket.to(currentMap).emit('attackEffect', {
    from: socket.id,
    target: monsterId,
    damage
  });

  // 击杀处理
  if (monster.hp <= 0) {
    const userId = playerInfo.player.userId;
    socket.to(currentMap).emit('chat', {
      type: 'system',
      text: `【系统】${userId} 击杀了 ${monsterId}！`,
      map: currentMap
    });

    // 3秒后重生
    setTimeout(() => {
      resetMonster(currentMap, monsterId);
      // 通知所有玩家刷新怪物状态
      socket.to(currentMap).emit('state', getMapState(currentMap));
    }, 3000);
  }

  // 同步最新状态
  socket.to(currentMap).emit('state', getMapState(currentMap));
}

module.exports = {
  handleAttack
};